require 'mu_api'
require 'rubygems'
require 'net/smtp'
require 'tlsmail'

# Whenever an analysis completes, archive the results and send
# notification using smtp mail
DEBUG = false
class AnalysisWatch
  def initialize
    @api = Mu_Api.new
    @eto = "somebody@somewhere.com"
    @archive_path = "/var/www/html/analysis_archives"
    @analysis_path = ""
  end
  
  def wait_for_running
    while 1
      uuid_list = @api.list_by_status("RUNNING")
      puts uuid_list if DEBUG
      unless uuid_list.nil?
        @api.run_uuid = uuid_list[0]
        break
      end
      sleep 15
    end
  end
  
  def wait_for_finished
    puts "Wait for #{@api.run_uuid} to complete" if DEBUG
    while 1
      status = @api.status
      break unless status =~ /(RUNNING|QUEUED)/
      sleep 15
    end
  end
  
  def fetch_archive
    archiving = @api.archive; puts "Archiving: #{archiving}" if DEBUG
    sleep 5
    # poll until the job is complete
    20.times do
      status = @api.archive("status"); puts "Status: #{status}" if DEBUG
      break if status == "Finished"
      sleep 5
    end
    # download the archive zip file, which is named by the job number
    zip = @api.archive("get"); puts "zip Filename: #{zip}" if DEBUG
    name = @api.get_name.gsub(/[^0-9A-Za-z.\-]/, '_')
    @analysis_path = @archive_path + "/" + name
    `unzip -o #{zip} -d #{@analysis_path}`; puts "Unzipped to: #{@analysis_path}" if DEBUG
  end

  # Send email notification via google.
  def notify
    server = "smtp.gmail.com"
    username = "user@gmail.com"
    password = "secret"
    root = Dir.glob("#{@analysis_path}/200*")[0]
    msg = <<EOM
From: #{username}
To: #{@eto}
MIME-Version: 1.0
Content-type: text/html
Subject: Analysis Complete message

EOM
    
    summary = File.read("#{root}/index.html")
    Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
    Net::SMTP.start(server, 25, 'pinot',username, password, :login) {|smtp|
      smtp.send_message msg + summary,
      username,
      eto
    } 
  end
end

w = AnalysisWatch.new
while 1
  w.wait_for_running
  w.wait_for_finished
  w.fetch_archive
  w.notify
end
